import datetime
from datetime import time
from pandas import DataFrame
def create_time_factor(df:DataFrame):
    
    flag=False
    
    # 时间因子    
    df.loc[:,'time_min'] = 0    # 7 每日的分钟线bar数量
    df.loc[:,'open_b'] = 0      # 8 每分钟的close/开盘的一个分钟线的open-1 收益率
    df.loc[:,'yes_H_pct']=0     # 9 当前close相对于昨日最高价的幅度
    df.loc[:,'yes_L_pct']=0     # 10 当前close相对于昨日最低价的幅度
    df.loc[:,'open_b_pct_AD']=0 # 11 有问题 开盘跳空 (已解决)
    df.loc[:,'OB5_pct_AD']=0    # 12 有问题 开盘后第五分钟，open相对于昨日收盘的突破价 (已解决)
    df.loc[:,'OB1_pct_AD']=0    # 13 开盘后第1分钟，open相对于昨日收盘的突破价
    df.loc[:,'yes_30min_pct_AD']=0    # 14 昨日最后30分钟动量，给下一日全日作为因子值

    df.loc[:,'time_min_9'] = 0    # 15 每日的分钟线bar数量 9点开始

    df.loc[:,'o_mom_9']=0# 16 今早上9点第一分钟 
    df.loc[:,'1min_vol_pct']=0 #17 第一分钟成交量除以昨日成交量 

    # 每日收盘bar
    close_bar = [i for i in df.index.strftime("%Y-%m-%d %H:%M:%S") if i.endswith('15:00:00')]
    
    # 每日9点bar
    open_9_bar = [i for i in df.index.strftime("%Y-%m-%d %H:%M:%S") if i.endswith('09:01:00')]

    # 每日开盘bar
    a=[]
    date_:datetime=df.index[-1]
    
    
    if date_.time()!=time(15,0):
        print(date_.time())
        print("进入第一个计算方式")
        for i in range(len(close_bar)):
            
            a.append(df.index[df.index.get_loc(close_bar[i])+1])
    else:
        print("进入第二个计算方式")
        for i in range(0,len(close_bar)-1):
            a.append(df.index[df.index.get_loc(close_bar[i])+1])
            print(a[-1])
        a=[df.index[0]]+a
    # print(close_bar)
    # print(a)

    # 每日14点30 bar
    b=[]
    for i in range(0,len(close_bar)):
        b.append(df.index[df.index.get_loc(close_bar[i])-30])

    print(len(a),len(close_bar),len(b))

    for i in range(len(a)):
        if i<len(a)-1:

            begin = df.index.get_loc(a[i])
            end = df.index.get_loc(a[i+1])
            print(close_bar[i+1])
            print(end)

            df.iloc[begin:end,7] = list(range(end-begin))
            df.iloc[begin:end,8] = df.iloc[begin:end,3] / df.iloc[begin,0] - 1


            #flag保证也就第一天全是0，后面都是有值的
            if i==0 and flag:
                df.iloc[begin:end,9] = df.iloc[begin:end,3] / maxx - 1
                df.iloc[begin:end,10] = df.iloc[begin:end,3] / minn - 1
                df.iloc[begin:end,11]=df.iloc[begin,0] / pre_close-1
                
                df.iloc[begin+4:end,12]=df.iloc[begin+4,0]/pre_close-1
               
                df.iloc[begin+1:end,13]=df.iloc[begin+1,0]/pre_close-1
            
                df.iloc[begin:end,17]=df.iloc[begin,4]/yesterday_volume-1
        #                     df.iloc[begin:end,14]=(df.iloc[begin,4]/df.iloc[begin,6])/yesterday_turnover_ratio
        #                     df.iloc[begin:end,15]=df.iloc[begin,6]/yesterday_open_interest-1

            if i>0:
                df.iloc[begin:end,9] = df.iloc[begin:end,3] / maxx - 1
                df.iloc[begin:end,10] = df.iloc[begin:end,3] / minn - 1
                df.iloc[begin:end,11] = df.iloc[begin,0] / df.iloc[begin-1,3] - 1#开盘价除以昨日收盘价
                df.iloc[begin+4:end,12] = df.iloc[begin+4,0] / df.iloc[begin-1,3] - 1
                df.iloc[begin+1:end,13] = df.iloc[begin+1,0] / df.iloc[begin-1,3] - 1

                df.iloc[begin:end,17]=df.iloc[begin,4]/yesterday_volume-1

            maxx = df.iloc[begin:end,1].max() #昨日最高价
            minn = df.iloc[begin:end,2].min() #昨日最低价

            yesterday_volume=df.iloc[begin:end,4].mean()
            yesterday_turnover_ratio=(df.iloc[begin:end,4]/df.iloc[begin:end,6]).mean()
            yesterday_open_interest=df.iloc[begin:end,6].mean()

        # 最后一天
        else:
            # maxx = df.iloc[end:,1].max() #昨日最高价
            # minn = df.iloc[end:,2].min() #昨日最低价
            end = df.index.get_loc(a[i])
            df.iloc[end:,7] = list(range(df.shape[0]-end))
            df.iloc[end:,8] = df.iloc[end:,3] / df.iloc[end,0] - 1
            df.iloc[end:,9] = df.iloc[end:,3] / maxx - 1
            df.iloc[end:,10] = df.iloc[end:,3] / minn - 1
            df.iloc[end:,11] = df.iloc[end,0] / df.iloc[end-1,3] - 1
            try:
                df.iloc[end+4:,12] = df.iloc[end+4,0] / df.iloc[end-1,3] - 1
            except:
                pass
            try:
                df.iloc[end+1:,13] = df.iloc[end+1,0] / df.iloc[end-1,3] - 1
            except:
                pass

            df.iloc[end:,17]= df.iloc[end,4]/yesterday_volume-1


        flag=True
        #存下pre_close 等各种昨日变量
        pre_close=df.iloc[-1,3]
        yesterday_volume=df.iloc[end:,4].mean()
        # yesterday_open_interest=df.iloc[end:,6].mean()
        # yesterday_turnover_ratio=(df.iloc[end:,4]/df.iloc[end:,6]).mean()

        # maxx = df.iloc[end:,1].max() #昨日最高价
        # minn = df.iloc[end:,2].min() #昨日最低价

    # 昨日最后半小时动量
    for i in range(1,len(b)):
        if i < len(b)-1:
            begin=df.index.get_loc(b[i-1])
            end=df.index.get_loc(b[i])
            begin_a = df.index.get_loc(a[i])
            end_a=df.index.get_loc(a[i+1])
            print(end_a)
            df.iloc[begin_a:end_a,14]=df.iloc[begin+30,3]/df.iloc[begin,3]-1

        else:
            end_a=df.index.get_loc(a[i])
            end=df.index.get_loc(b[i-1])
            df.iloc[end_a:,14]=df.iloc[end+30,3]/df.iloc[end,3]-1
#                 print('最后一天单独处理：',df.index[end],df.index[end+30])

#         ##9点的因子      
    a = open_9_bar

    for i in range(len(a)):
        if i<len(a)-1:
            begin = df.index.get_loc(a[i])
            end = df.index.get_loc(a[i+1])

            df.iloc[begin:end,15] = list(range(end-begin))

            df.iloc[begin:end,16]=df.iloc[begin,3]/df.iloc[begin,0]-1

        else:
            end=df.index.get_loc(a[i])
            df.iloc[end:,15] = list(range(df.shape[0]-end))

            df.iloc[end:,16]=df.iloc[end,3]/df.iloc[end,0]-1

    df['open_b_BOOL'] = (df['open_b']>0)*1
    df['yes_30_BOOL'] = (df['yes_30min_pct_AD']>0)*1
    df['yes_L_pct_BOOL'] = (df['yes_L_pct']>0)*1
    df['yes_H_pct_BOOL'] = (df['yes_H_pct']>0)*1

    return df